<script setup>
import userService from '@/api/modules/user.js'
import { useCountDown } from '@/hooks/useCountDown.js'
import useUserStore from '@/store/modules/user.js'
import { decrypt, encrypt } from '@/utils/jsencrypt.js'
import messageHelper from '@/utils/messageHelper.js'
import { storage } from '@/utils/storage.js'
import { useRoute } from 'vue-router'

const emit = defineEmits(['login-success'])
const loginRef = ref(null)
const type = ref('password')
const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
  smsCode: '',
  phonenumber: '',
})

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入手机号码' }, { validator: validatePhone, trigger: 'blur' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }, { min: 6, max: 18, message: '密码长度在6到18个字符', trigger: 'blur' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
  phonenumber: [{ required: true, trigger: 'blur', message: '请输入手机号码' }, { pattern: /^1[3-9|]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  smsCode: [{ required: true, trigger: 'blur', message: '请输入验证码' }, { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }, { pattern: /^\d+$/, message: '验证码只能包含数字', trigger: 'blur' }],
}

const { countDown, isRunning, start, stop, reset } = useCountDown(60)

// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)
const codeUrl = ref('')

const loading = ref(false)
const route = useRoute()

const userStore = useUserStore()
watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

onMounted(() => {
  getCaptchaImage()
  getCookies()
})

function getCookies() {
  const username = storage.get('username')
  const password = storage.get('password')
  const rememberMe = storage.get('rememberMe')
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  }
}

function getCaptchaImage() {
  userService.captchaImage().then((res) => {
    const data = res.data
    captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${data.img}`
      loginForm.value.uuid = data.uuid
    }
  })
}

function validatePhone(rule, value, callback) {
  if (value === 'admin') {
    callback()
  }
  else {
    const regex = /^1[3-9]\d{9}$/
    if (regex.test(value)) {
      callback()
    }
    else {
      callback(new Error('请输入正确的手机号码'))
    }
  }
}

function switchType(val) {
  type.value = val
}

function getSmsCode() {
  const formRef = loginRef.value
  formRef.validateField('phonenumber', (valid) => {
    if (valid) {
      userService.captchaSms({
        phonenumber: loginForm.value.phonenumber,
        type: 1,
      }).then((res) => {
        reset()
        start()
        messageHelper.message.success('验证码发送成功，请注意查收')
      })
    }
  })
}

function handleLogin() {
  const loginForm = loginRef.value
  loginForm.validate((valid) => {
    if (valid) {
      if (type.value === 'phone') {
        handlePhoneLogin()
      }
      else {
        handlePasswordLogin()
      }
    }
  })
}

function handlePasswordLogin() {
  loading.value = true
  // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
  if (loginForm.value.rememberMe) {
    storage.set('username', loginForm.value.username)
    storage.set('password', encrypt(loginForm.value.password))
    storage.set('rememberMe', loginForm.value.rememberMe)
  }
  else {
    // 否则移除
    storage.remove('username')
    storage.remove('password')
    storage.remove('rememberMe')
  }
  const params = loginForm.value
  userStore.authLogin(params).then((res) => {
    emit('login-success')
  }).catch((err) => {
    getCaptchaImage()
  }).finally(() => {
    loading.value = false
  })
}

function handlePhoneLogin() {
  loading.value = true
  const params = loginForm.value
  userStore.authSmsLogin(params).then((res) => {
    emit('login-success')
  }).catch((err) => {
    messageHelper.message.error(err)
  }).finally(() => {
    loading.value = false
  })
}
</script>

<template>
  <el-form
    ref="loginRef"
    :model="loginForm"
    :rules="loginRules" class="login-form item-container" label-position="top"
    :hide-required-asterisk="true"
  >
    <template v-if="type === 'phone'">
      <el-form-item prop="phonenumber" label="手机号码">
        <el-input
          v-model="loginForm.phonenumber"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输入手机号码"
        >
          <template #prefix>
            <svg-icon name="ri:smartphone-line" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="smsCode" label="验证码">
        <el-input
          v-model="loginForm.smsCode"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输入手机验证码"
          class="!w-[72%]"
        >
          <template #prefix>
            <svg-icon name="ri:shield-check-line" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <el-button
          size="large"
          class="!w-[25%] ml-3"
          :disabled="countDown < 60 && countDown > 0"
          @click="getSmsCode"
        >
          {{ (countDown === 60 || countDown === 0) ? '获取验证码' : `${countDown}秒后重试` }}
        </el-button>
      </el-form-item>
    </template>
    <template v-else>
      <el-form-item prop="username" label="手机号">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输入手机号码"
        >
          <template #prefix>
            <svg-icon name="ri:smartphone-line" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="请输入密码"
          show-password
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <svg-icon name="ri:lock-line" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code" label="验证码">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="请输入验证码"
          style="width: 67%"
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <svg-icon name="ri:shield-check-line" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCaptchaImage">
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">
        记住密码
      </el-checkbox>
    </template>
    <el-form-item style="width:100%;">
      <el-button
        v-ripple
        :loading="loading"
        size="large"
        type="primary"
        class="!w-full !text-[16px] transition-all duration-300 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
        @click.prevent="handleLogin"
      >
        <span v-if="!loading">登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>
      <div v-if="register" style="float: right;">
        <router-link class="link-type" to="/register">
          立即注册
        </router-link>
      </div>
    </el-form-item>
    <div class="switch-container hover:text-[var(--primary-color)] transition-all duration-300 cursor-pointer">
      <span v-if="type !== 'password'" class="tip" @click="switchType('password')">
        账号密码登录
      </span>
      <span v-if="type !== 'phone'" class="tip" @click="switchType('phone')">
        手机验证码登录
      </span>
    </div>
  </el-form>
</template>

<style scoped lang="scss">
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
